package com.wzh.product.search;

import com.alibaba.fastjson.JSONObject;
import com.wzh.product.dao.ProductDao;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author WZH
 * @title: ProductSearch
 * @projectName t1_1.22
 * @description:
 * @date 2022/1/25
 */
@Component
public class ProductSearch {
    @Autowired
    private ProductDao productDao;

    @Autowired
    private RestHighLevelClient client;

    @Scheduled(cron = "0/30 * * * * ?")
    public void scheduled() throws Exception {
        System.out.println("30秒更新");
        BulkRequest request = new BulkRequest("product02");
        productDao.selectList(null).forEach(item->{
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(item.getId().toString());
            String jsonString = JSONObject.toJSONString(item);
            indexRequest.source(jsonString, XContentType.JSON);
            request.add(indexRequest);
        });
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
    }
}
